package org.neframework.webtest.util.office.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.neframework.webtest.util.office.excel.util.ExcelCheckTools;

/**
 * 操作Excel表格的功能类
 */
public class ExcelReadTools {
	private POIFSFileSystem fs;
	private HSSFWorkbook wb;
	private HSSFSheet sheet;
	private HSSFRow row;

	/**
	 * 读取Excel表格表头的内容
	 * 
	 * @return String 表头内容的数组
	 */
	public String[] readExcelTitle(InputStream is) {
		try {
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (IOException e) {
			e.printStackTrace();
		}
		sheet = wb.getSheetAt(0);
		row = sheet.getRow(0);
		// 标题总列数
		int colNum = row.getPhysicalNumberOfCells();
		System.out.println("colNum:" + colNum);
		String[] title = new String[colNum];
		for (int i = 0; i < colNum; i++) {
			// title[i] = getStringCellValue(row.getCell((short) i));
			title[i] = ExcelCheckTools.getCellFormatValue(row.getCell((short) i));
		}
		return title;
	}

	/**
	 * 读取Excel数据内容
	 * 
	 * @return Map 包含单元格数据内容的Map对象
	 */
	public List<List<Object>> readExcelContent(File file) {
		List<List<Object>> list = new ArrayList<List<Object>>();

		InputStream is = null;
		try {
			is = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			return list;
		}

		try {
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (IOException e) {
			e.printStackTrace();
		}
		sheet = wb.getSheetAt(0);
		// 得到总行数
		int rowNum = sheet.getLastRowNum();
		System.err.println("总行数-----------" + rowNum);

		row = sheet.getRow(1);
		int colNum = row.getPhysicalNumberOfCells();
		// 正文内容应该从第二行开始,第一行为表头的标题
		for (int i = 1; i <= rowNum + 1; i++) {
			row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			int j = 0;
			List<Object> cont = new ArrayList<Object>();
			while (j < colNum) {
				cont.add(ExcelCheckTools.getCellFormatValue(row.getCell((short) j)));
				j++;
			}

			if (!ExcelCheckTools.isNull(cont)) {
				list.add(cont);
			}
		}
		if (is != null) {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public static void main(String[] args) {
		// 对读取Excel表格标题测试
		System.err.println("excel 在该工具类下面.");
		ExcelReadTools excelReader = new ExcelReadTools();

		// 对读取Excel表格内容测试
		List<List<Object>> list = excelReader.readExcelContent(new File("F:\\UC下载\\behaf_model.xls"));
		for (List<Object> list2 : list) {
			for (Object object : list2) {
				System.err.println(object.getClass());
			}
		}

		System.err.println("获得Excel表格的内容:");
		System.err.println(list);

	}
}